package com.example.book.service.impl;


import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.book.entity.Book;
import com.example.book.entity.Chapter;
import com.example.book.entity.Type;
import com.example.book.entity.dto.BookDto;
import com.example.book.mapper.BookMapper;
import com.example.book.mapper.ChapterMapper;
import com.example.book.service.IBookService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.book.service.ITypeService;
import com.example.common.dtos.ResponseResult;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 凡哥哥
 * @since 2023-10-01
 */
@Service
@Slf4j
@Transactional
public class BookServiceImpl extends ServiceImpl<BookMapper, Book> implements IBookService {
    @Autowired
    private BookMapper bookMapper;
    @Autowired
    private ITypeService typeService;

    /**
     * 图书分页,信息回显
     *
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @Override
    public ResponseResult<Page> pageInfo(Integer page, Integer pageSize, String name) {
        Page<Book> page1 = new Page(page, pageSize);
        LambdaQueryWrapper<Book> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Book::getIsDelete, 1);
        queryWrapper.like(Book::getName, name);
        Page<Book> bookPage = this.page(page1, queryWrapper);
        List<Book> bookList = bookPage.getRecords().stream().map(item -> {
            //获取图书类型id
            Integer typeId = item.getType();
            //根据图书类型id查询类型表
            Type type = typeService.getById(typeId);
            //获取图书类型
            String typeName = type.getType();
            //赋值
            item.setTypeName(typeName);
            return item;
        }).collect(Collectors.toList());
        bookPage.setRecords(bookList);
        return ResponseResult.okResult(bookPage);
    }

    /**
     * 根据图书ID查询图书
     *
     * @param ids
     * @return
     */
    @Override
    public ResponseResult bookIdList(Long[] ids) {
        List<Book> bookList = new ArrayList<>();
        for (Long id : ids) {
            Book book = bookMapper.selectById(id);
            //获取图书类型id
            Integer typeId = book.getType();
            //根据图书类型id查询类型表
            Type type = typeService.getById(typeId);
            //获取图书类型
            String typeName = type.getType();
            //赋值
            book.setTypeName(typeName);
            bookList.add(book);
        }
        return ResponseResult.okResult(bookList);
    }

    @Override
    public ResponseResult bookStatusInfo(Book book) {

       
        return null;
    }

    /**
     * 添加图书
     *
     * @param book
     * @return
     */
    @Override
    public ResponseResult addBook(Book book) {
        if (!Objects.isNull(book)){
            book.setCreateTime(LocalDateTime.now());
            bookMapper.insert(book);
        }
        return ResponseResult.okResult("添加作品成功");
    }
    @Autowired
    private ChapterMapper chapterMapper;
    /**
     * 查询作者的作品
     *
     * @param authorId 作者id
     * @return
     */
    @Override
    public ResponseResult authorBook(Long authorId) {
        LambdaQueryWrapper<Book> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Book::getAuthorId,authorId);
        List<Book> bookList = bookMapper.selectList(lqw);
        List<BookDto> bookDtoList = new ArrayList<>();
        for (Book book : bookList) {
            Long bookId = book.getId();
            BookDto bookDto = BookDto.builder().build();
            BeanUtils.copyProperties(book,bookDto,"description");
            LambdaQueryWrapper<Chapter> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Chapter::getBookId, bookId)
                    .orderByDesc(Chapter::getCreateTime)
                    .last("LIMIT 1");
            Chapter chapter = chapterMapper.selectOne(queryWrapper);
            if (!ObjectUtil.isNull(chapter)){
                bookDto.setChapterNumber(chapter.getChapterNumber());
                bookDto.setChapterTitle(chapter.getChapterTitle());
                System.err.println(bookDto);
                bookDtoList.add(bookDto);
            }else {
                bookDtoList.add(bookDto);
            }
        }
        return ResponseResult.okResult(bookDtoList);
    }

    /**
     * 查询作者的最新作品
     *
     * @param authorId 作者id
     * @return
     */
    @Override
    public ResponseResult authorBookByTime(Long authorId) {
        LambdaQueryWrapper<Book> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Book::getAuthorId, authorId);
        lqw.orderByDesc(Book::getCreateTime); // 根据创建时间降序排序
        List<Book> bookList = bookMapper.selectList(lqw);
        BookDto bookDto = BookDto.builder().build();
        if (!CollectionUtils.isEmpty(bookList)) {
            Book latestBook = bookList.get(0); // 获取列表中的第一本书，即最新的一本书
            BeanUtils.copyProperties(latestBook, bookDto, "description");
            LambdaQueryWrapper<Chapter> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Chapter::getBookId, latestBook.getId())
                    .orderByDesc(Chapter::getCreateTime)
                    .last("LIMIT 1");
            Chapter latestChapter = chapterMapper.selectOne(queryWrapper);
            if (latestChapter != null) {
                bookDto.setChapterNumber(latestChapter.getChapterNumber());
                bookDto.setChapterTitle(latestChapter.getChapterTitle());
                List<String> textList = chapterMapper.getTotalText(authorId, latestChapter.getBookId());
                Long totalCount = 0L;
                for (String text : textList) {
                    totalCount += Long.valueOf(text);
                }
                bookDto.setWordCount(latestChapter.getWordCount());
                bookDto.setTotalCount(String.valueOf(totalCount));
            }
        }
        return ResponseResult.okResult(bookDto);
    }


    /**
     * 修改图书状态
     *
     * @param id
     * @return
     */
    public ResponseResult updateStatus(Long id) {
        Book book = bookMapper.selectById(id);
        if (!book.getStatus()) {
            book.setStatus(true);
        } else {
            book.setStatus(false);
        }
        bookMapper.updateById(book);
        return ResponseResult.okResult(book);
    }

    /**
     * 删除图书
     *
     * @param ids
     * @return
     */
    @Override
    public ResponseResult deleteBooks(int[] ids) {
        //进行逻辑删除
        for (int id : ids) {
            Book book = this.getById(id);
            Boolean status = book.getStatus();
            if (status){
                return ResponseResult.errorResult(500,"图书状态正常不能删除");
            }
            LambdaUpdateWrapper<Book> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.eq(Book::getId, id);
            updateWrapper.set(Book::getIsDelete, 0);
            this.update(updateWrapper);
        }
        return ResponseResult.okResult("图书信息删除成功");
    }



}
